<?php
namespace App\Http\Controllers\Manage\Article;

use App\Ext\Common\UploadImage;
use App\Http\Controllers\Manage\CommonController;
use App\Model\Msg\Msg;

class MsgController extends CommonController{
    /**
     * 广告列表页
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => 'ID',
            'title' => '标题',
            'img_name' => '图片',
            'create_time' => '添加时间'
        ];
        $viewData = [];
        $viewData['title'] = '商城广告管理';
        $viewData['nav'] = $this->navTab('msg', 'main');
        # 列表查询字段
        $viewData['field'] = $field;
        # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '添加站内信',
                'route' => route('manage.article.msg.resource.create')
            ]
        ];
        # 行表操作菜单
        $viewData['option_row'] = [
            'edit' => [
                'title' => '修改',
                'route' => 'manage.article.msg.resource.edit'
            ],
            'trash' => [
                'title' => '删除',
                'route' => 'manage.article.msg.resource.destroy',
            ]
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [
            'trash' => [
                'method' => 'DELETE',
                'title' => '删除站内信',
                'msg' => '确定要删除站内信吗'
            ]
        ];
        #列表数据
        $msg = new Msg;
        $viewData['list'] = $this->constraintSelect($msg, $field);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 删除站内信
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $result = Msg::where('id', $id)->delete();
        if ($result) {
            return redirect()->back()->with('success', '删除成功!');
        }
        return redirect()->back()->with('error', '删除失败!');
    }

    /**
     * 创建站内信页面
     * @return mixed
     */
    public function create()
    {
        # 表单元素
        $param = [
            'title' => [
                'type' => 'text',
                'col' => '12',
                'name' => '标题',
            ],
            'picture' => [
                'type' => 'file',
                'col' => '12',
                'name' => '站内信图片',
                'accept' => 'image',
                'ratio' => '1',
            ],
            'content' => [
                'type' => 'editor',
                'col' => '12',
                'name' => '站内信内容',
                'upload_image' => route('manage.article.msg.upload'),
            ],
        ];
        $viewData = [];
        $viewData['title'] = '添加站内信';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.article.msg.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'return' => [
                'name' => '返回站内信列表',
                'type' => 'button',
                'route' => route('manage.article.msg.resource.index')
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     * 创建广告操作
     * @return mixed
     */
    public function store()
    {
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写标题!');
        }
        if (!$this->request->hasFile('picture')) {
            return redirect()->back()->with('error', '请选择图片!');
        }
        $picture = $this->request->file('picture');
        $file = $this->uploadImage($picture, 'msg');
        if (isset($file['error'])) {
            return redirect()->back()->with('error', $file['error']);
        }
        $msg = new Msg;
        $msg->title = $this->request->input('title');
        $msg->content = $this->request->input('content');
        $msg->create_time = currentTime();
        if (isset($file['file'])) {
            $msg->img_name = $file['file']['name'];
        }
        if ($msg->save()) {
            return redirect()->route('manage.article.msg.resource.index')->with('success', '信息创建成功!');
        }
        return redirect()->back()->with('error', '广告创建失败!');
    }

    /**
     * 修改信息页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        # 查询记录数据
        $data = Msg::find($id);
        $picture = array();
        $picture[] = [
            'name' => $data->img_name,
            'file' => $this->domain . $this->path['msg'] . $data->img_name,
            'id' => $id,
        ];
        $picture = json_encode($picture);
        # 表单元素
        $param = [
            'title' => [
                'type' => 'text',
                'col' => '12',
                'name' => '标题',
                'value' => $data->title
            ],
            'picture' => [
                'type' => 'file',
                'col' => '12',
                'name' => '图片',
                'accept' => 'image',
                'value' => $picture
            ],
            'content' => [
                'type' => 'editor',
                'col' => '12',
                'name' => '内容',
                'upload_image' => route('manage.article.msg.upload'),
                'value' => $data->content
            ],
        ];
        $viewData = [];
        $viewData['title'] = '修改信息';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.article.msg.resource.update', ['id' => $id]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'return' => [
                'name' => '返回信息列表',
                'type' => 'button',
                'route' => route('manage.article.msg.resource.index')
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }

    /**
     * 修改广告信息操作
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写广告标题!');
        }
        $msg = Msg::find($id);
        if ($this->request->hasFile('picture')) {
            $picture = $this->request->file('picture');
            $file = $this->uploadImage($picture, 'msg');
            if (isset($file['file'])) {
                $msg->img_name = $file['file']['name'];
            }
        }
        $msg->title = $this->request->input('title');
        $msg->content = $this->request->input('content');
        $msg->create_time = currentTime();
        if ($msg->save()) {
            return redirect()->route('manage.article.msg.resource.index')->with('success', '修改成功!');
        }
        return redirect()->back()->with('error', '修改失败!');
    }

    /*public function upload()
    {
        $data = [];
        if ($this->request->hasFile('image')) {
            $file = $this->request->file('image');
            $image = $this->uploadFile($file, $this->path['msg']);
            $data['state'] = 'SUCCESS';
            $data['file'] = $this->assets['domain'] . '/' . $this->path['msg'] . '/' . $image;
            return response()->json($data);
        }
        $data['state'] = '文件上传失败!';
        return response()->json($data);
    }
    private function uploadFile($file, $path = '')
    {
        if ($file->isValid()) {
            $fileName = time() . substr(mt_rand(), 5) . '.' . $file->getClientOriginalExtension();
            $file->move($path, $fileName);
            return $fileName;
        }
        return false;
    }*/
    public function upload()
    {
        $response = array();
        if (count($_FILES) < 1) {
            $response['state'] = '没有接受到上传的文件!';
            return response()->json($response);
        }
        $files = $this->request->file('image');
        $images = array();
        foreach ($files as $file) {
            # 原始文件名
            $originalName = $file->getClientOriginalName();
            # 新文件名
            $fileName = time() . substr(mt_rand(), 5);
            $fileName = $fileName . '.' . $file->getClientOriginalExtension();
            # 验证图片大小
            $sizeMax = formatBytes($file->getMaxFilesize());
            $sizeMax = floor($sizeMax);
            $fileSize = formatBytes($file->getClientSize());
            if ($fileSize > $sizeMax) {
                $response['state'] = '文件"' . $originalName . '"容量为' . $fileSize . 'MB，超过上传文件大小限制，文件上传的最大限制为' . $sizeMax . 'MB';
                return response()->json($response);
            }
            # 验证图片格式
            $image = new UploadImage();
            $mime = ['jpg','jpeg','png']; # 文件类型限制
            if (!$image->checkMime($file, $mime)) {
                $response['state'] = '上传的文件格式限制为"jpg,jpeg,png"';
                return response()->json($response);
            }

            # 保存文件对象
            $imageParam = [
                'max' => ['w' => 1024, 'watermark' => $this->filePath['water_mark']],
                'small' => ['w' => 24, 'h' => 24],
            ];
            $result = $image->save($file, $this->path['content_msg'], $fileName, $imageParam);
            # 上传到云存储
            if ($result) $images[] = $result;
        }
        $response['state'] = 'SUCCESS';
        $response['file'] = $images;
        return response()->json($response);
    }

}